package com.java.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.HospitalFeignClient;
import com.java.PatientFeignClient;
import com.java.common.helper.HttpRequestHelper;
import com.java.config.exceptioin.YyghException;
import com.java.config.result.ResultCodeEnum;
import com.java.instant.MqConst;
import com.java.mapper.OrderMapper;
import com.java.model.order.*;
import com.java.model.user.Patient;
import com.java.model.user.UserInfo;
import com.java.model.vo.MsmVo;
import com.java.model.vo.OrderMqVo;
import com.java.model.vo.ScheduleOrderVo;
import com.java.model.vo.SignInfoVo;
import com.java.service.OrderService;
import com.java.service.RabbitService;
import com.java.service.WeixinService;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private WeixinService weixinService;


    //医院订单
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long saveOrder(String scheduleId, String patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);
        if(patient == null ){
            throw  new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //获取排班信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        //获取签名校验信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        if(scheduleOrderVo == null ){
            throw  new YyghException(ResultCodeEnum.TIME_NO);
        }
        //如果挂号时间比当前时间前 那么挂号就失败
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
        || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        final OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
        //订单编号
        String outTradeNo = System.currentTimeMillis()+""+new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setHosScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(Long.parseLong(patientId));
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //保存订单
        this.save(orderInfo);

        //封装 就诊人的信息
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());

        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        //获取时间戳
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String signKey = signInfoVo.getSignKey();
        String sign = HttpRequestHelper.getSign(paramMap, signKey);
        paramMap.put("sign", sign);
        //向医院平台请求保存订单接口 并返数据
        JSONObject result  = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        if(result.getInteger("code") == 200){
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            Integer hosRecordId = jsonObject.getInteger("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            //更新订单
            orderInfo.setHosRecordId(String.valueOf(hosRecordId));
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            //更新
            orderMapper.updateById(orderInfo);

            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq信息更新号源和短信通知
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            final String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") +
                    (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            //使用特殊方式Put
            HashMap<String, Object> param = new HashMap<String, Object>(){{
                put("title",orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount",orderInfo.getAmount());
                put("reserveDate",reserveDate);
                put("name",orderInfo.getPatientName());
                put("quiteTime",new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            //mq发送
            //rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
            //参数接收
        }else{
            throw new YyghException(result.getString("message"),ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    //统计每天的预约次数
    @Override
    public Map<String,Object> getOrderList(OrderCountQueryVo orderCountQueryVo) {
        Map<String, Object> map = new HashMap<>();
        //[{realeaseDate:2021-07-01,count:10},{realeaseDate:2021-07-02,count:20}]
        List<OrderCountVo> orderCountVoList = orderMapper.selectOrderCount(orderCountQueryVo);
        //日期拆分[2021-07-01,2021-07-02]
        List<Object> dateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //次数拆分[10,20]
        List<Integer> counts = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("date",dateList);
        map.put("counts",counts);
        return map;
    }

    //获取订单详情
    @Override
    public OrderInfo getOrders(String orderId) {
        return orderMapper.selectById(orderId);
        //return packgeOrder(orderInfo);
    }

    //查询分页
    @Override
    public IPage<OrderInfo> selectByPage(Page<OrderInfo> page, OrderQueryVo orderQueryVo,Long userId) {
        String hosname = orderQueryVo.getKeyword();//医院名称
        Long patientId = orderQueryVo.getPatientId();//就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus();//订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        //对条件值非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(hosname)){
            wrapper.like("hosname",hosname);
        }
        if(!StringUtils.isEmpty(patientId)){
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)){
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)){
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)){
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)){
            wrapper.le("create_time",createTimeEnd);
        }
        wrapper.eq("user_id",userId);
        IPage<OrderInfo> orderInfoIPage = orderMapper.selectPage(page, wrapper);
        orderInfoIPage.getRecords().stream().forEach(orderInfo->{
            this.packgeOrder(orderInfo);
        });
        return orderInfoIPage;
    }

    //就诊提醒
    @Override
    public void patientTips() {
        //根据当天的时间查询所有定单
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        //ne不等于
        wrapper.ne("order_status",OrderStatusEnum.CANCLE);
        //查询出当天所有的定单
        List<OrderInfo> orderInfoList = orderMapper.selectList(wrapper);
        //遍历每一个订单并把定单封装到msmvo中
        for(OrderInfo order : orderInfoList){
            //封装短信类中
            MsmVo msmVo = new MsmVo();
            //联系人姓名
            msmVo.setPhone(order.getPatientPhone());
            String reserveString = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd") + (order.getReserveTime() == 0 ? "上午" : "下午");
            //封装msmvo的param
            HashMap<String, Object> map = new HashMap<>();
            map.put("title",order.getHosname()+"|"+order.getDepname()+"|"+order.getTitle());
            map.put("reserveDate",order.getReserveDate());
            map.put("name",order.getPatientName());
            msmVo.setParam(map);
            //出发发送短信的业务
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.QUEUE_MSM_ITEM,msmVo);
        }

    }

    //取消订单
    @Override
    public Boolean cancelOrder(Long orderId) {
        //获取订单
        OrderInfo orderInfo = orderService.getById(orderId);
        //查看订单的预约时间是否已经过了当前时间 如果过了那就不能取消订单
        DateTime quetTime = new DateTime(orderInfo.getQuitTime());
        if(quetTime.isBeforeNow()){
            throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);//当前时间不能取消预约
        }
        //获取医院地址和秘钥
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if(signInfoVo==null){
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);//参数不正确
        }
        Map<String, Object> map = new HashMap<>();
        map.put("hoscode",orderInfo.getHoscode());
        map.put("hosRecordId",orderInfo.getHosRecordId());
        map.put("timestamp",HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(map, signInfoVo.getSignKey());
        map.put("sign",sign);
        JSONObject result = HttpRequestHelper.sendRequest(map, signInfoVo.getApiUrl() + "/order/updateCancelStatus");
        //返回结果如果不为200抛出异常
        if(result.getInteger("code")!=200){
            throw new YyghException(result.getString("message"),ResultCodeEnum.FAIL.getCode());
        }else{
            //是支付 退款 查询订单支付状态 如果是以支付就退款
            if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus()){
                //如果是 调用微信的退款
                Boolean isRefund = weixinService.refund(orderId);
                if(!isRefund){
                    throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);//取消订单失败
                }
            }
            //退款成功后更新订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            orderService.updateById(orderInfo);

            //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，
            // 不设置可预约数与剩余预约数，接收端可预约数减1即可
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getHosScheduleId());
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("SMS_194640722");
            //安排日期
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> paramMap = new HashMap<String, Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(paramMap);
            orderMqVo.setMsmVo(msmVo);
            //rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.QUEUE_ORDER,orderMqVo);
            return true;
        }
    }

    public OrderInfo packgeOrder(OrderInfo orderInfo){
        String statusName = OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus());
        orderInfo.getParam().put("statusName",statusName);
        return orderInfo;
    }
}
